angular.module('user', ['head-toast'])

.controller 'LoginCtrl', ($scope, $state, $http, userData ,$stateParams,$ionicHistory,showToast,$ionicPopup) ->
    user = userData.get()
    _.extend $scope,
        loginData: {
            username:user?.username
            password:user?.password
        }
        processing: false
        error:
            notifing: false
            msg: undefined
        formValidation: ->
            Nemail =  $scope.loginData.username.match(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/) == null
            Ntel = $scope.loginData.username.match(/^((13[0-9])|(15[^4,\D])|(18[0-9])|(14[5,7])|(17[0,6-8]))\d{8}$/)==null
            if Nemail and Ntel
                showToast '请输入正确的手机号或邮箱地址'
                $scope.processing = false
                return false
            else
                return true
        clear: (type) ->
            $scope.loginData[type] = ''
            $scope.focus = type
        goBack: ->
            $ionicHistory.goBack()
        num: ->

        login: ->
            if $scope.processing == true then return
            $scope.processing = true
            uploadObj = _.extend {action: 'login'}, $scope.loginData
#                13564377888
#HF951753
            if $scope.formValidation()
                $http.post('/users/',uploadObj)
                .success (resp) ->
                    console.log resp
                    if resp.status == '0'
                        $scope.processing = false
                        userData.set {username:$scope.loginData.username,password:$scope.loginData.password}
                        userData.setToken resp.userid
                        $ionicHistory.nextViewOptions {disableBack: true}
                        $state.go 'tab.home',{reload:true}
                    else
                        $scope.processing = false
                        showToast resp.msg
                .error ->
                    $scope.processing = false
                    showToast '发生了网络错误,请稍后重试!'
        goForgotPwd: ->
                $state.go 'forgot-pwd'

.controller 'RegisterCtrl', ($scope, $state, $http, $ionicHistory, $ionicPopup, userData,$location,$localStorage,$stateParams,showToast) ->

    defaultData =
        action:'register'
        mobile : undefined
        password    : undefined
        phoneValid  : undefined
        regcode: undefined
        referee:undefined
    showNotify = (msg) ->
        $scope.notify = {show: true, msg: msg}
        barTimer = setTimeout (->
            clearTimeout barTimer
            $scope.notify.show = false
        ), 3000
    _.extend $scope,
        processing: false
        remainTime: 0
        regData: defaultData
        refereeData:
#            inputData:''
            refereeName:''
        formValidation: ->
            console.log $scope.regData.referee
            Numb = $scope.regData.referee.match(/^[0-9]*$/) == null
            Nucod = $scope.regData.referee.match(/^[A-Za-z]+$/) == null
            Nuall = $scope.regData.referee.match(/^(?![a-z]+$|[0-9]+$)^[a-zA-Z0-9]{6,}$/) == null
            if $scope.regData.password.match(/^[0-9a-zA-Z]{6,16}$/) == null
                showToast '请输入由6-16位英文字母或数字组成的密码'
                return false
            else if $scope.regData.password != $scope.regData.confirm
                showToast '两次输入的新密码不一样,请重新输入!'
                return false
            else if Numb and Nucod and Nuall
                showToast '推荐人编码错误!正确的由字母或数字或字母+数字组成'
                return false
            else
                return true
        goBack: ->
            console.log 222
            $ionicHistory.goBack()
        goLogin: ->
            if $stateParams.origin == 'pick-product'
                $state.go 'login',{origin: 'pick-product'}
            else
                $state.go 'login'
        register: ->
#            if $scope.processing == true then return
#            $scope.processing = true
            if $scope.formValidation()
                $http.post('/users/',$scope.regData)
                    .success (resp) ->
                        if resp.status == '0'
                            $scope.processing = false
                            $scope.regData = defaultData
                            userData.setToken resp.userid
                            if $stateParams.origin == 'pick-product'
                                $ionicHistory.goBack()
                            else
                                _.defer -> $state.go 'tab.home',{reload:true}
                        else
                            $scope.processing = false
                            showNotify resp.msg
                    .error ->
                        $scope.processing = false
                        showNotify '注册失败，无法登陆'
        getReferee: ->
            defaultData.referee = '1000'
            $scope.showReferee()
#            $scope.refereeData.inputData='1000'
#        clearReferee: ->
#            $scope.refereeData.inputData=defaultData.referee
        showReferee:->
            reg=/^[0-9]{4,6}$/
            if reg.test(defaultData.referee)
#                defaultData.referee=$scope.refereeData.inputData
                $http.get '/users',params:{action:'getpartnername',userid:userData.getToken(),referee:defaultData.referee}
                .success (resp) ->
                    if resp.status=='0'
                        $scope.refereeData.refereeName=resp.partnername
                    else
                        $scope.refereeData.refereeName=''
                .error (err) ->
                    $scope.refereeData.refereeName=''
            else
                $scope.refereeData.refereeName=''
        getVerifyCode: ->

            $scope.remainTime = 60
            timer = setInterval (->
                $scope.remainTime--
                $scope.$apply()
                if $scope.remainTime == 0
                    clearInterval timer
            ), 1000
            $http.post('/users/',{action:'sendcode',mobile:$scope.regData.mobile,regcode:$scope.regData.regcode,stype:'0'})
            .success (resp) ->
                if resp.status == '0'
                    showNotify '短信验证码已发送'
                else
                    showNotify resp.msg
            .error ->
                showNotify '服务器处理失败，请稍后重试'
        cantReceive: ->
            confirmPopup = $ionicPopup.confirm {
                template: '请检查手机号码是否正确。<br/>如正确，但长时间未收到短信，请拨打免费客服电话获取验证码。'
                cancelText: '取消'
                okText: '致电客服'
            }
            confirmPopup.then (res) ->
                if res then window.open('tel:4000022699', '_system')

.controller 'ForgotPwdCtrl' , ($scope, $state, $http, $ionicHistory, $ionicPopup,showToast,userData) ->
    defaultData = {mobile: undefined, verify: undefined, action: 'register',password: undefined, pwdcode: undefined }
    showNotify = (msg) ->
        $scope.notify = {show: true, msg: msg}
        barTimer = setTimeout (->
            clearTimeout barTimer
            $scope.notify.show = false
        ), 3000
    _.extend $scope,
        remainTime: 0
        showNotice: false
        data: defaultData
        regData: defaultData
        formValidation: ->
            if $scope.regData.password.match(/^[0-9a-zA-Z]{6,16}$/) == null
                showToast '请输入由6-16位英文字母或数字组成的密码'
                return false
            else if $scope.regData.password != $scope.regData.confirm
                showToast '两次输入的新密码不一样,请重新输入!'
                return false
            else
                return true
        goBack: ->
            $ionicHistory.goBack()
        login: ->
            # TODO 发送请求到后端
            console.log $scope.data

            $scope.data = defaultData
            $state.go 'tab.home'
        getVerifyCode: ->

            $scope.showNotice = true
            barTimer = setTimeout (->
                clearTimeout barTimer
                $scope.showNotice = false
            ), 3000

            $scope.remainTime = 60
            timer = setInterval (->
                $scope.remainTime--
                $scope.$apply()
                if $scope.remainTime == 0
                    clearInterval timer
            ), 1000
            $http.post('/users/',{action:'sendcode',mobile:$scope.regData.mobile,stype:'1'})
            .success (resp) ->
                if resp.status == '0'
                    showNotify '短信验证码已发送'
                else
                    showNotify '后台处理异常，请稍后重试'
            .error ->
                showNotify '服务器处理失败，请稍后重试'
        cantReceive: ->
            confirmPopup = $ionicPopup.confirm {
                template: '请检查手机号码是否正确。<br/>如正确，但长时间未收到短信，请拨打免费客服电话获取验证码。'
                cancelText: '取消'
                okText: '致电客服'
            }
            confirmPopup.then (res) ->
                if res
                    window.open('tel:400510678', '_system')
                else
                    console.log('cancel');
        register: ->
            if $scope.formValidation()
                $http.post('/users/',{action:'findpass',mobile:$scope.regData.mobile, pwdcode:$scope.regData.pwdcode, password:$scope.regData.password})
                .success (resp) ->
                    if resp.status == '0'
                        uploadObj = {
                            action:'login'
                            username:$scope.regData.mobile
                            password:$scope.regData.password
                        }
                        $http.post('/users/',uploadObj)
                        .success (resp) ->
                            console.log resp
                            if resp.status == '0'
                                $scope.processing = false
                                userData.reset()
                                $ionicHistory.clearCache()
                                userData.set {username:$scope.regData.username,password:$scope.regData.password}
                                console.log userData.get()
                                userData.setToken resp.userid
                                $ionicHistory.nextViewOptions {disableBack: true}
                                $state.go 'tab.home',{reload:true}
                            else
                                $scope.processing = false
                                showError resp.msg
                        .error ->
                            $scope.processing = false
                            showError '发生了网络错误，请稍后重试'
                    else
                        $scope.processing = false
                        showToast '网络异常没能修改成功!'
                .error ->
                    $scope.processing = false
                    showToast '网络异常,请检查您的网络!'
.controller 'SetPwdCtrl', ($scope, $state, $http, $ionicHistory) ->

